// import Taro from "@tarojs/taro";
import { ACCESS_TOKEN_CODE, COMMUNITY_CODE_KEY } from "@/constants/index";
import Taro from "@tarojs/taro";
import axios from "axios";
// import { LOGIN_KEY } from "../../constant";

// const { accessToken } = useLogin();
const createRequest = (baseURL) => {
  const instance = axios.create({
    baseURL,
  });

  instance.interceptors.request.use(
    (config) => {
      config.headers["Tenant-Code"] = Taro.getStorageSync(COMMUNITY_CODE_KEY);
      config.headers["Authorization"] = `Bearer ${Taro.getStorageSync(
        ACCESS_TOKEN_CODE
      )}`;
      return config;
    },
    (error) => {
      console.log(error);
    }
  );

  instance.interceptors.response.use(
    (response: any) => {
      const { status, data } = response;
      if (status === 200) {
        const { code } = data;
        if (code === 401) {
          Taro.navigateTo({
            url: "/packageA/pages/login/index",
          });

          return Promise.reject(data);
        }
        return Promise.resolve(data);
      } else {
        return Promise.reject(data);
      }
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  return instance;
};

const mpRequest = createRequest("https://www.hicc.info/api/mp");
const cmsRequest = createRequest("http://www.hicc.info:6002/api/cms");

export { mpRequest, cmsRequest };
